package datahelper

import (
	"../luahelper"
	json2 "encoding/json"
	lua "github.com/yuin/gopher-lua"
	"io/ioutil"
)

var data_file string

func init() {
	data_file = "Data.json"
}

func RegisterFunc_4lua(l *lua.LState) {
	func_table := l.SetFuncs(l.NewTable(), map[string]lua.LGFunction{
		"Get":  Get_4lua,
		"Set":  Set_4lua,
		"Load": Load_4lua,
		"Save": Save_4lua,
	})

	l.SetGlobal("DataHelper", func_table)
}

func Get_4lua(l *lua.LState) int {
	// count = DataHelper.Get("1")

	key := l.ToString(1)
	value := dataHelperInstance.GetData(key)
	l.Push(lua.LString(value))
	return 1
}

func Set_4lua(l *lua.LState) int {
	// DataHelper.Set("1", "2")

	key := l.ToString(1)
	value := l.ToString(2)
	dataHelperInstance.SetData(key, value)
	return 0
}

func Load_4lua(l *lua.LState) int {
	// DataHelper.Load()

	json, err := ioutil.ReadFile(data_file)
	if  err != nil {
		return luahelper.PushErrorMessage(l, err.Error())

	}

	var mapping map[string]string
	if err = json2.Unmarshal(json, &mapping); err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	if mapping != nil && len(mapping) != 0 {
		for k, v := range mapping {
			dataHelperInstance.SetData(k, v)
		}
	}

	return luahelper.PushStatus(l, true)
}

func Save_4lua(l *lua.LState) int {
	// DataHelper.Save()

	json, err := json2.Marshal(dataHelperInstance.dataMapping)
	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	err = ioutil.WriteFile(data_file, json, 0644)
	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	return luahelper.PushStatus(l, true)
}
